<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot-scope="scope" slot="shopName">
        <el-tag v-if="scope.row.shopType===0" type="warning">{{scope.row.shopName}}</el-tag>
        <el-tag v-else-if="scope.row.shopType===1" type="info">{{scope.row.shopName}}</el-tag>
        <el-tag v-else-if="scope.row.shopType===2" type="danger">{{scope.row.shopName}}</el-tag>
        <el-tag v-else-if="scope.row.shopType===3" type="success">{{scope.row.shopName}}</el-tag>
        <el-tag v-else >{{scope.row.shopName}}</el-tag>
      </template>
      <template slot-scope="{type,disabled}" slot="spuDescribeForm">
        <avue-ueditor   v-model="form.spuDescribe"
                      :options="ueditorOptions"></avue-ueditor>
      </template>
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.spu_delete"
                   @click="handleDelete">删 除
        </el-button>


      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text"
                   icon="el-icon-document"
                   size="small"
                   plain
                   style="border: 0;background-color: transparent !important;"
                   @click="handleShowAttr(scope.row.id,scope.row.spuCategory)">商品属性
        </el-button>
        <el-button type="text"
                   icon="el-icon-setting"
                   size="small"
                   plain
                   style="border: 0;background-color: transparent !important;"
                   @click="handleShowSku(scope.row.id,scope.row.spuCategory)">销售规格
        </el-button>
        <el-button type="text"
                   v-if="scope.row.status===0"
                   icon="el-icon-top"
                   size="small"
                   plain
                   style="border: 0;background-color: transparent !important;"
                   @click="handleAudit(scope.row.id)">提交审核
        </el-button>
        <el-button type="text"
                   v-if="scope.row.status===1"
                   icon="el-icon-top"
                   size="small"
                   plain
                   style="border: 0;background-color: transparent !important;"
                   @click="handleCancel(scope.row.id)">取消审核
        </el-button>
        <el-button type="text"
                   v-if="scope.row.status===2"
                   icon="el-icon-top"
                   size="small"
                   plain
                   style="border: 0;background-color: transparent !important;"
                   @click="handlePutaway(scope.row.id)">上架
        </el-button>
        <el-button type="text"
                   v-if="scope.row.status===3"
                   icon="el-icon-bottom"
                   size="small"
                   plain
                   style="border: 0;background-color: transparent !important;"
                   @click="handleSoldOut(scope.row.id)">下架
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="商品属性配置"
               :visible.sync="attrBox"
               width="60%">

      <avue-crud :data="attrData"
                 :option="attrOption"
                 @current-change="attrCurrentChange"
                 @on-load="attrLoad"
                 :table-loading="attrLoading"
                 ref="attrCrud"
                 @row-save="attrRowSave"
                 @row-del="attrRowDel"
                 @row-update="attrRowUpdate"
                 @search-change="attrSearchChange"
                 @search-reset="attrSearchReset"
                 @selection-change="attrSelectionChange"
                 :page="attrPage"
                 @size-change="attrSizeChange">
      </avue-crud>
    </el-dialog>
    <el-dialog title="商品规格配置"
               :visible.sync="skuBox"
               width="60%">

      <avue-crud :data="skuData"
                 :option="skuOption"
                 @on-load="skuLoad"
                 :table-loading="skuLoading"
                 ref="skuCrud"
                 @row-del="skuRowDel"
                 @row-update="SkuRowUpdate"
                 @search-change="skuSearchChange"
                 @search-reset="skuSearchReset"
                 @current-change="skuCurrentChange"
                 :page="skuPage"
                 @size-change="skuSizeChange"
                 >
        <template slot="menuLeft">
          <el-tag type="danger">您不能在此添加规格,但可以删除和修改</el-tag>

        </template>
      </avue-crud>
    </el-dialog>


  </basic-container>
</template>

<script>
  import { getDetail,status, add, update, remove , getPage ,putaway,soldOut} from "@/api/product/spu";
  import { addAttr, updateAttr, removeAttr,getAttrPage ,} from "@/api/product/attrValue";
  import {getSkuPage, updateSku, removeSku} from "@/api/product/sku";
  import {mapGetters} from "vuex";
  import { getAttrByCategory} from "@/api/category/category";
  import avueUeditor from 'avue-plugin-ueditor'
  export default {
    component:{
      avueUeditor
    },
    data(){
      return {
        //富文本配置
        ueditorOptions:{
          action: '/api/ocm-resource/oss/endpoint/put-file',
          customConfig: {},//wangEditor编辑的配置
          props: {
            res: "data",
            url: "link"
          },
        },
        attrBox: false,
        skuBox: false,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          excelBtn:true,
          addBtn:false,
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          column: [
            {
              label: "标题",
              prop: "spuTitle",
              search: true,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "副标题",
              prop: "spuInfo",
              rules: [{
                required: true,
                message: "请输入副标题",
                trigger: "blur"
              }]
            },

            {
              label: "所属分类",
              prop: "spuCategory",
              search:true,
              type: "tree",
              dicUrl: "/api/ocm-product/category/list",
              props: {
                label: "categoryName",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请输入所属分类",
                trigger: "click"
              }]
            },
            {
              label: "邮费",
              prop: "spuPostage",
              rules: [{
                required: true,
                message: "请输入邮费",
                trigger: "blur"
              }]
            },
            {
              label: "视频",
              prop: "spuVideo",
              accept:"video/mp4",
              type: "upload",
              listType: 'picture-img',
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: '/api/ocm-resource/oss/endpoint/put-file',
              tip: '只能上传mp4视频，且不超过50M',
              hide:true,
              rules: [{
                required: false,
                message: "请输入视频",
                trigger: "blur"
              }]
            },
            {
              label: "主图",
              prop: "spuThumb",
              type: "upload",
              listType: 'picture-img',
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: '/api/ocm-resource/oss/endpoint/put-file',
              tip: '只能上传jpg/png图片，且不超过500kb',
              rules: [{
                required: true,
                message: "请输入主图（图片数组第一张）",
                trigger: "blur"
              }]
            },
            {
              label: "图片",
              hide:true,
              dataType: 'string',
              type: "upload",
              row:true,
              span:24,
              listType: 'picture-card',
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: '/api/ocm-resource/oss/endpoint/put-file',
              tip: '只能上传jpg/png图片，且不超过500kb',
              prop: "spuImages",
              rules: [{
                required: true,
                message: "请输入图片",
                trigger: "blur"
              }]
            },
            {
              label: "详情",
              hide:true,
              formslot:true,
              prop: "spuDescribe",
              dataType: 'string',
              type: "upload",
              row:true,
              span:24,
              listType: 'picture-card',
              propsHttp: {
                res: 'data',
                url: 'link',
              },

              action: '/api/ocm-resource/oss/endpoint/put-file',
              tip: '只能上传jpg/png图片，且不超过500kb',
              rules: [{
                required: true,
                message: "请输入图片详情",
                trigger: "blur"
              }]
            },
            {
              label: "商店",
              prop: "shopName",
              search:true,
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入店铺ID",
                trigger: "blur"
              }]
            },
            {
              label: "库存总数",
              prop: "stockNumber",
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入邮费",
                trigger: "blur"
              }]
            },
            {
              label: "锁定库存",
              prop: "stockLock",
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入邮费",
                trigger: "blur"
              }]
            },
            {
              label: "销量",
              prop: "saleCount",
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入邮费",
                trigger: "blur"
              }]
            },
            {
              label: "当前状态",
              search:true,
              prop: "status",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              disabled:true,
              dicUrl: "/api/ocm-system/dict/dictionary?code=product_status",
              type: 'select',
              rules: [{
                required: true,
                message: "请输入0已下架 1待上架 2审核中 3已上架",
                trigger: "blur"
              }]
            },
            {
              label: "商品类型",
              search:true,
              prop: "spuType",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dicUrl: "/api/ocm-system/dict/dictionary?code=product_type",
              type: 'select',
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "审核时间",
              hide:true,
              editDisplay: false,
              prop: "auditTime",
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "审核员",
              hide:true,
              prop: "auditUser",
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "remark",
              hide:true,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            },
            {
              label: "审核备注",
              hide:true,
              prop: "auditRemark",
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入审核备注",
                trigger: "blur"
              }]
            },
          ]
        },
        /*以下为attr列表所需curd数据*/
        spuId:0,
        attrLoading:true,
        categoryId:0,
        attrQuery:{},
        attrSelectionList: [],
        attrData:[],
        attrPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },

        attrOption:{
          menu:true,
          menuWidth: 150,
          viewBtn: false,
          editBtn: true,
          addBtn: true,
          delBtn: true,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          tree: true,
          border: true,
          index: true,
          selection: true,
          column: [
            {
              label: "属性",
              prop: "attrId",
              type: "tree",
              hide:true,
              dicData: [],
              editDisplay:false,
              props: {
                label: "attrName",
                value:"id"
              },
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "属性名",
              prop: "attrName",
              search: true,
              addDisplay:false,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },{
              label: "属性值",
              prop: "attrValue",
              search: true,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
          ]
        },
        /*以下为sku列表所需curd数据*/
        skuId:0,
        skuLoading:true,
        skuQuery:{},
        skuSelectionList: [],
        skuData:[],
        skuPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },

        skuOption:{
          menu:true,
          menuWidth: 150,
          viewBtn: false,
          editBtn: true,
          addBtn: false,
          delBtn: true,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          tree: true,
          border: true,
          index: true,
          selection: true,
          column: [
            {
              label: "标题",
              prop: "skuTitle",
              search: true,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "价格",
              prop: "skuPrice",
              search: true,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "规格",
              prop: "saleAttr",
              editDisplay:false,
              search: true,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "图片",
              prop: "skuImage",
              type: "upload",
              listType: 'picture-img',
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              canvasOption:{
                text:'ocm',


              },
              action: '/api/ocm-resource/oss/endpoint/put-file',
              tip: '只能上传jpg/png图片，且不超过500kb',
              rules: [{
                required: true,
                message: "请输入主图（图片数组第一张）",
                trigger: "blur"
              }]
            },
            {
              label: "销量",
              prop: "skuSales",
              editDisplay:false,
              rules: [{
                required: false,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "库存总数",
              prop: "stockNumber",
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入邮费",
                trigger: "blur"
              }]
            },
            {
              label: "锁定库存",
              prop: "stockLock",
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入邮费",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.spu_add, false),
          viewBtn: this.vaildData(this.permission.spu_view, false),
          delBtn: this.vaildData(this.permission.spu_delete, false),
          editBtn: this.vaildData(this.permission.spu_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleAudit(id){
        status({'id':id,'status':1}).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
      },
      handleCancel(id){
        status({'id':id,'status':0}).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
      },
      attrLoad(attrPage){
        getAttrPage(attrPage.currentPage, attrPage.pageSize,
          Object.assign(this.attrQuery,
            {
              'spuId_equal':this.spuId,
              'skuId_equal':'0'
            })
        ).then(res => {
          this.attrLoading=true;
          const data = res.data.data;
          this.attrData = data.records;
          this.attrLoading = false;
          this.attrPage.total = data.total;

          getAttrByCategory(1, 999, {'r.categoryId_equal':this.categoryId}).then(res => {
            const data = res.data.data;
            const column = this.findObject(this.attrOption.column, "attrId");
            //过滤掉已有属性
            column.dicData = data.records.filter(t=>{
              let res=true
              this.attrData.forEach(x=>{
                if(x.attrId===t.id)
                  res=false
              })
              return res !== false;
            });
          });
        });

      },
      skuLoad(){
        getSkuPage(this.skuPage.currentPage, this.skuPage.pageSize,
          Object.assign(this.skuQuery,
            {'k.spuId_equal':this.spuId})
        ).then(res => {
          this.skuLoading=true;
          const data = res.data.data;
          this.skuData = data.records;
          this.skuLoading = false;
          this.skuPage.total = data.total;
        });
      },
      handlePutaway(id){
        putaway(id).then(()=>{
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "上架成功"
          });
        }, error => {
          window.console.log(error);
        })
      },
      handleSoldOut(id){
        soldOut(id).then(()=>{
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "下架成功"
          });
        }, error => {
          window.console.log(error);
        })
      },
      handleShowSku(id,cate){
        this.spuId=id
        this.categoryId=cate
        this.skuLoad()
        this.skuBox = true

      },
      handleShowAttr(id,cate){
        console.log(id)
        this.spuId=id
        this.categoryId=cate
        this.attrLoad(this.attrPage)
        this.attrBox = true
      },

      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      // skuRowSave(row, done, loading) {
      //   add(row).then(() => {
      //     done();
      //     this.onLoad(this.page);
      //     this.$message({
      //       type: "success",
      //       message: "操作成功!"
      //     });
      //   }, error => {
      //     window.console.log(error);
      //     loading();
      //   });
      // },
      skuRowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeSku(row.id);
          })
          .then(() => {
            this.skuLoad();
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      SkuRowUpdate(row, index, done, loading) {
        updateSku(row).then(() => {
          done();
          this.skuLoad();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      attrRowUpdate(row, index, done, loading) {
        row.spuId=null
        row.skuId=null
        updateAttr(row).then(() => {
          done();
          this.attrLoad(this.attrPage)
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      attrRowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeAttr(row.id);
          })
          .then(() => {
            this.attrLoad(this.attrPage)
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      attrRowSave(row, done, loading){

        row.spuId=this.spuId
        console.log(row)
        addAttr(row).then(() => {
          done();
          this.attrLoad(this.attrPage)
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        // if (["edit", "view"].includes(type)) {
        //   getDetail(this.form.id).then(res => {
        //     this.form = res.data.data;
        //   });
        // }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        if(this.query.shopName!==null){
          this.query['s.shopName']=this.query.shopName
          this.query.shopName=null
        }
        console.log(this.query)
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      attrSearchReset() {
        this.attrQuery = {};
        this.attrLoad(this.page);
      },
      attrCurrentChange(currentPage){
        this.attrPage.currentPage = currentPage;
      },
      attrSizeChange(pageSize){
        this.attrPage.pageSize = pageSize;
      },

      attrSearchChange(params, done) {
        this.attrQuery = params;
        console.log(this.attrQuery)
        this.attrPage.currentPage = 1;
        this.attrLoad(this.attrPage);
        done();
      },
      attrSelectionChange(list) {
        this.attrSelectionList = list;
      },
      skuSearchChange(params, done) {
        this.skuQuery = params;

        this.skuLoad();
        done();
      },
      skuSearchReset() {
        this.skuQuery = {};
        this.skuLoad();
      },
      skuCurrentChange(currentPage){
        this.skuPage.currentPage = currentPage;
      },
      skuSizeChange(pageSize){
        this.skuPage.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
